package com.game.thrones.aop;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

//@Aspect
//@Component
public class PermissionAOP {
	private Logger logger = LoggerFactory.getLogger(PermissionAOP.class);

	@Around("execution(* com.oembedler.moon.graphql.boot.GraphQLServerController.*(..))")
	public Object getPermission(ProceedingJoinPoint proceedingJoinPoint) {
		Object result = null;
		logger.info("进入拦截器");
		System.out.println("Completed: " + proceedingJoinPoint);
		HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes())
				.getRequest();
		String remoteAddr = getIpAddress(request);
		String userAgent = request.getHeader("user-agent");
		String requestUri = request.getRequestURI();
		String method = request.getMethod();
		Map<String, String[]> paramMap = request.getParameterMap();
		StringBuffer params = new StringBuffer();
		if (paramMap != null && !paramMap.isEmpty()) {
			for (Map.Entry<String, String[]> param : paramMap.entrySet()) {
				if ("".equals(params.toString())) {
					params.append(param.getKey() + "=");
				} else {
					params.append("&" + param.getKey() + "=");
				}

				String paramValue = "";
				if (param.getValue() != null && param.getValue().length > 0) {
					paramValue = param.getValue()[0];
				}
				params.append(paramValue);
			}
		}
		logger.info("ip address:" + remoteAddr);
		logger.info("useragent:" + userAgent);
		logger.info("url:" + requestUri);
		logger.info("request method:" + method);
		logger.info("method params:" + params.toString());
		logger.info("---------------------------------");
		try {
			if (result == null) {
				result = proceedingJoinPoint.proceed();
			}
		} catch (Throwable e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return result;
	}

	public static String getIpAddress(HttpServletRequest request) {
		String ip = request.getHeader("X-Forwarded-For");
		if (StringUtils.isNotEmpty(ip) && !"unKnown".equalsIgnoreCase(ip)) {
			// 多次反向代理后会有多个ip值,第一个ip才是真实ip
			int index = ip.indexOf(",");
			if (index != -1) {
				return ip.substring(0, index);
			} else {
				return ip;
			}
		}
		ip = request.getHeader("X-Real-IP");
		if (StringUtils.isNotEmpty(ip) && !"unKnown".equalsIgnoreCase(ip)) {
			return ip;
		}
		return request.getRemoteAddr();
	}
}